package nuist.hanniko.stu.webbackend.util;

import com.alibaba.fastjson.JSONObject;
import nuist.hanniko.stu.webbackend.model.LwM2m.request.*;

public class RequestSerializer {
    public static JSONObject serialize2Json(BaseRequest request) {
        JSONObject requestObject = new JSONObject();

        // parse "req" param object
        JSONObject reqParamObject = new JSONObject();
        reqParamObject.put("kind", request.getKind());
        reqParamObject.put("path", request.getPath());

        if (request instanceof ReadRequest) {
            reqParamObject.put("contentFormat", ((ReadRequest) request).getContentFormat());
        } else if (request instanceof ObserveRequest) {
            reqParamObject.put("contentFormat", ((ObserveRequest) request).getContentFormat());
        } else if (request instanceof WriteRequest) {
            JSONObject node = new JSONObject();
            node.put("kind", ((WriteRequest) request).getNodeKind());
            node.put("value", ((WriteRequest) request).getNodeValue());

            reqParamObject.put("mode", ((WriteRequest) request).getMode());
            reqParamObject.put("node", node);
        } else if (request instanceof ExecuteRequest) {
            reqParamObject.put("parameters", ((ExecuteRequest) request).getParameters());
        }

        requestObject.put("ep", request.getEndpoint());
        requestObject.put("req", reqParamObject);

        return requestObject;
    }
}
